<?php
namespace Common\Controller;
use Think\Controller;
use Common\Model\UserRelationModel;
use Common\Model\MemberModel;
use Home\Controller\PublicController;
use Think\Model;
class CommonController extends Controller {
    protected $config;

    //protected $trade;
    //头部全部用到个人信息的部分ajax给值，其它程序用到的部分 用getuserinfo方法替换 member属性
   	protected $member;
    protected $dividendConfig;
	protected $currency;
	protected $AppID='wx911b7cf7b6169721';
	protected $AppSecret='b0cb4af091c7a02f7e278e0b842e3a23';
 	public function _initialize(){
 		$config = M('Config')->select();
 		foreach ($config as $k=>$v){
 			$config_re[$v['key']] = $v['value'];
 		}
 		$this->config=$config_re;
		
     }
     
     // echo language('中国', 'zh', 'en');
     public function upload($file){
          
         switch($file['type'])
         {
             case 'image/jpeg': $ext = 'jpg'; break;
             case 'image/gif': $ext = 'gif'; break;
             case 'image/png': $ext = 'png'; break;
             case 'image/tiff': $ext = 'tif'; break;
             default: $ext = ''; break;
         }
         if (empty($ext)){
             return false;
         }
         $upload = new \Think\Upload();// 实例化上传类
         $upload->maxSize   =     3145728 ;// 设置附件上传大小
         $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
         $upload->savePath  =      './Public/Uploads/'; // 设置附件上传目录
         // 上传文件
         $info   =  $upload->uploadOne($file);
         $data = [];
         if(!$info) {
             // 上传错误提示错误信息
             $data = [
                 'status'=>-1,
                 'msg'=>$upload->getError(),
             ];
         }else{
             // 上传成功
             $pic=$info['savepath'].$info['savename'];
             $url='/Uploads'.ltrim($pic,".");
             $data = [
                 'status'=>1,
                 'url'=>$url,
             ];
         }
         return $data;
     }
     /**
      * 处理分页
      */
     public function DoPage($page,$num){
         if(empty($page)){
             $page = 1;
         }
         if(empty($num)){
             $num = 10;
         }
         $data = [
             'page'=>$page,
             'num'=>$num,
             'limit'=>($page-1)*$num,
         ];
         return $data;
     }
     public function getCode(){
         $lenth = 20;
        $code =  $this->get_random($lenth, '123456789ABCDEFGHIJKLMNPQRSTUVWXYZ');
         while(M('Words')->where(array('code'=>$code))->find()){
             $code = $this->getCode();
         }
         return $code;
     }
     function get_random($length, $chars = '0123456789') {
         $hash = '';
         $max = strlen($chars) - 1;
         for($i = 0; $i < $length; $i++) {
             $hash .= $chars[mt_rand(0, $max)];
         }
         return $hash;
     }
     public function getUrl(){
         $lenth = 40;
         $url =  $this->get_random($lenth, 'QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890');
         while(M('Miyao')->where(array('url'=>$url))->find()){
             $url = $this->getUrl();
         }
         return $url;
     }
     public function getQianbaoUrl(){
         $lenth = 35;
         $url =  $this->get_random($lenth, 'QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890');
         while(M('Wallet_url')->where(array('url1'=>$url))->find()){
             $url = $this->getUrl();
         }
         return $url;
     }
     public function getQianbaoUrl1(){
         $lenth = 35;
         $url =  $this->get_random($lenth, 'QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890');
         while(M('Wallet_url')->where(array('url2'=>$url))->find()){
             $url = $this->getUrl();
         }
         return $url;
     }
     public function getMemberGroup($member_id){
         return $member_id%10;
     }
     //获取配置项数值
     public function getConfig(){
         $config = M('Config')->select();
         foreach ($config as $k=>$v){
             $config_re[$v['key']] = $v['value'];
         }
         return $config_re;
     }
     /**
      * 检测输入的验证码是否正确，
      * @param string $code 用户输入的验证码字符串
      * @param string $id
      * @return boolean
      */
     public function checkVerify($code, $id = ''){
     	$verify = new \Think\Verify();
     	return $verify->check($code,$id);
     }
	//使用curl的GET请求数据  返回数组
	protected function curl_get($http){
		//初始化 
			$ch = curl_init();
			//设置选项，包括URL
			curl_setopt($ch, CURLOPT_URL, $http);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
			//执行并获取HTML文档内容
			$output = curl_exec($ch);
			//释放curl句柄
			curl_close($ch);
			//打印获得的数据
			$result = json_decode($output,true);
			return $result;
	}
	//代数奖
	public function runDaishuMoney($user,$up_user,$k,$level,$project_money){
	    if($k>20){
	        return;
	    }
	    $MEMBER = new MemberModel();
	    $up_note = M('Member')->where(['member_id'=>$up_user['uid']])->find();
	    //查询上级 推荐关系
	    $USERRELATION = new UserRelationModel();
	    $up = $USERRELATION->getUpByPid($up_user['pid']);
	    $up_user_up = M('Member')->where(['member_id'=>$up_user['pid']])->find();
	    $user_from = M('Member')->where(['member_id'=>$up['uid']])->find();
	    if(!$up||!$up_user_up){
	        return;
	    }
	    //直推上级是否可以拿代数奖代理
	    if($k==1&&$up_note['level'] != 1){
	        $this->runYejiMoney($up_note,$user,1,$up_note['level'],$project_money);
	    }
	    //再向上
	    if($user_from['level'] != 1){
	        $this->runYejiMoney($user_from,$user,1,$user_from['level'],$project_money);
	    }
	    $k++;
	    $this->runDaishuMoney($user,$up,$k,$level,$project_money);
	
	}
	//发放代数
	public function runYejiMoney($user,$user_from,$type,$level,$project_money){
	    //矿主
	    $money = $this->getConfig()['daishu_kuangzhu'];
	    if($level == 3||$level == 4||$level == 5){
	        //高级矿主
	        $money = $this->getConfig()['daishu_gaoji'];
	    }
	    $jiang = $money*$project_money;
	    $r[]=$this->setUserMoney($user['member_id'],$jiang,1,2);
	    $r[] = $this->addFinance($user['member_id'],4,'来自'.$user_from['username'].'团队奖励',$jiang,1,2);
	    //发起人和合伙人 还能得分红
	    if($level == 4||$level == 5){
	        //发起人 合伙人
	        if($level==4){
	            $fenhong_bili= $this->getConfig()['hehuoren_fenhong'];
	        }else{
	            $fenhong_bili= $this->getConfig()['faqiren_fenhong'];
	        }
	        $fenhong_jiang = $fenhong_bili*$project_money;
	        $r[]=$this->setUserMoney($user['member_id'],$fenhong_jiang,1,2);
	        $r[] = $this->addFinance($user['member_id'],4,'来自'.$user_from['username'].'分红奖励',$fenhong_jiang,1,2);
	    }
	}
	//分红奖
	public function runFenhongMoney($user,$user_from,$type,$level,$project_money){
	    //矿主
	    $money = $this->getConfig()['daishu_kuangzhu'];
	    if($level == 3||$level == 4||$level == 5){
	        //高级矿主
	        $money = $this->getConfig()['daishu_gaoji'];
	    }
	    $jiang = $money*$project_money;
	    $r[]=$this->setUserMoney($user['member_id'],$jiang,1,2);
	    $r[] = $this->addFinance($user['member_id'],4,'来自'.$user_from['username'].'团队奖励',$jiang,1,2);
	}
	//记录 自动程序的表
	public function addProject($uid,$project,$money_type,$money){
	    $data['uid'] 		= $uid;
	    $project_no = getProjectNo();
	    while(M('Project_log')->where(array('project_no'=>$project_no))->find()){
	        $project_no = getProjectNo();
	    }
	    $data['project_no'] 	= $project_no;
	    $data['money'] 		    = $project['shouyi'];
	    $data['project_id']		= $project['id'];
	    $data['suanli']         = $project['shouyi']*$this->config['shengchanli'];
	    $data['status']         = 0;
	    $data['add_time'] 	    = time();
	    $r = M('Project_log')->add($data);
	    return $r;
	}
	//加上线的团队人数
	public function addTeamNum($user){
	    $uid = $user['member_id'];
	    $USERRELATION = new UserRelationModel();
	    //加团队人数
	    $USERRELATION->addTeamNum($uid,1);
	    if($user['pid']){
	    //查询上级 推荐关系
	    $USER = new MemberModel();
	    $up = $USER->getUserByUid($user['pid']);
	    }
	    if(!$up){
	        return;
	    }
	    $this->addTeamNum($up);
	}
	public function addZtNum($user){
		$uid = $user['member_id'];
		$USERRELATION = new UserRelationModel();
		//加团队人数
		$USERRELATION->addZhituiNum($uid,1);
		if($user['pid']){
			//查询上级 推荐关系
			$USER = new MemberModel();
			$up = $USER->getUserByUid($user['pid']);
		}
		if(!$up){
			return;
		}
		$this->addTeamNum($up);
	}
	public function addTeamYeji($user,$num,$currency_id){
		$uid = $user['member_id'];
		M('user_relation')->where('uid ='.$user['member_id'])->setInc('num'.$currency_id,$num);
		if($user['pid']){
			//查询上级 推荐关系
			$USER = new MemberModel();
			$up = $USER->getUserByUid($user['pid']);
		}
		if(!$up){
			return;
		}
		$this->addTeamYeji($up,$num,$currency_id);
	}
	public function reduceTeamYeji($user,$num,$currency_id){
		$uid = $user['member_id'];
		M('user_relation')->where('uid ='.$user['member_id'])->setDec('num'.$currency_id,$num);
		if($user['pid']){
			//查询上级 推荐关系
			$USER = new MemberModel();
			$up = $USER->getUserByUid($user['pid']);
		}
		if(!$up){
			return;
		}
		$this->addTeamYeji($up,$num,$currency_id);
	}
    /**
     * 微信登录
     */
    public function weiXinLogin($aaa = "") {
		
         $appid = $this->AppID;
         $secret = $this->AppSecret;
        if (!isset($_GET["code"])) {
             $this->userAuthorize($aaa);
         }
         $code = $_GET["code"];
		 // dump($code);
         // 获取access_token、openid等其他信息
         $get_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
         $res = file_get_contents($get_token_url);
         dump();die;
         // 解析返回结果
		 //dump($res);die;
         $json_obj = json_decode($res, true);
		  // dump($json_obj);
		 
		  // dump($_SESSION);
		  // return json_decode($res, true);
         if (!empty($json_obj['access_token'])) {
             // 根据openid和access_token查询用户信息
			 // dump($json_obj);
             return $json_obj;
         }else {
             
             return -1001;
         }
    }
    public function userAuthorize($a) {
    	$redirect_uri = urlencode('http://pan2.money654.com');
    	//dump($redirect_uri);die;
    	// $get_token_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->AppID."& redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_base#wechat_redirect";
    	$get_token_url = "http://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->AppID."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo#wechat_redirect";
    	// dump($get_token_url);die;
    	header("Location:".$get_token_url);
    		
    		
    }
	/**
	*获取用户信息  $field 查询字段   str
	*/
	protected function get_user($field){
		$where['openid'] = $_SESSION['openid'];
		$member = M('Member')->Field($field)->where($where)->find();
		return $member;
	}
	
    /**
     *个人资金优化  只有上面调用
     */
    protected function getuserallmoney($member_id,$currency_id){
    	if (empty($currency_id)){
    		$data['forzen_num'] = $this->member['forzen_rmb'];
    		$data['num'] = $this->member['rmb'];
    	}else {
    		$data= M('Currency_user')->Field('forzen_num,num')->where("member_id={$member_id} and currency_id=$currency_id")->find();
    	}
    	return $data;
    }
	
    /**
     * 查询个人信息
     */
    protected  function getUserInfo($userId){
    	if(!empty($userId)){
    		$member=M("Member")->field('member_id,openid,email,pwd,pid,pwdtrade,nick,name,cardtype,idcard,phone,ip,reg_time,login_ip,login_time,rmb,forzen_rmb,head,profile,province,city,job,is_lock,status,dividend_num,threepwd,(rmb+forzen_rmb) as count')->where("member_id='{$_SESSION['member_id']}'")->find();
    	}else {
    		$member=array();
    	}
    	return $member;
    }
	/**
 	* 检测是否需要进行信息填写(补全)
 	*/
	protected function  User_status(){
		header("Content-type:text/html;charset=utf-8");
		if(!$this->checkLogin()){
			$this->redirect('Login/index');
		}
		$list = M('Member')->Field('status')->where(array('member_id'=>session('member_id')))->find();
		if($list['status']==0){
			session('STATUS',0);
			$this->redirect('ModifyMember/modify','',1,"<script>alert('请填写个人信息')</script>");
			exit();
		}
	}

	/**
	 * 查询钱包余额
	 * @param unknown $port_number 端口号
	 * @return Ambigous <number, unknown> 剩余的余额
	 */
	protected  function get_qianbao_balance($currency){
		require_once 'App/Common/Common/easybitcoin.php';
		$bitcoin = new \Bitcoin($currency['rpc_user'],$currency['rpc_pwd'],$currency['rpc_url'],$currency['port_number']);
		$money=$bitcoin->getinfo();
		$num=empty($money['balance'])?0:$money['balance'];
		return $num;
	}

    /**
     * 根据ID返回具体分类
     * @param string $id
     * @return boolean|array $list;
     */

    public function getCatById($id=null){
        if (empty($id)){
            return false;
        }
        return M('Article_category')->Field('id,name,keywords,status')->where("id=$id")->find();
    }

    /**
     * 返回指定父类下面的二级分类
     * @param string $parentId
     * @return boolean|array $list;
     */
    public function getChildCatByParentCat($parentId=null){
        if (empty($parentId)){
            return false;
        }
        return M('Article_category')->Field('id,name,keywords,status')->where("parent_id=$parentId")->select();
    }
    /**
     * 获取当前币种的信息
     * @param int $id 币种id
     * @return 24H成交量 24H_done_num  24H成交额 24H_done_money 24H涨跌 24H_change 7D涨跌  7D_change
     * @return 最新价格 new_price 买一价 buy_one_price 卖一价 sell_one_price 最高价 max_price 最低价 min_price
     */

    public function getCurrencyMessageById($id){
		if(S('trade_info_'.$id)){
			$data = S('trade_info_'.$id);
		}else{
			$time=time();
			$m = M('Trade_'.$id)->Field('price')->order('add_time desc')->find();
			$data['new_price'] = $m['price'];
			//************************************************************************
			$rs=M('Trade_'.$id)->order('add_time desc')->find();
			//24H涨跌
			$re=M('Trade_'.$id)->where("add_time<$time-60*60*24")->order('add_time desc')->find();
			if ($re['price']!=0){
				$data['24H_change']=sprintf("%.2f", ($rs['price']-$re['price'])/$re['price']*100);
				if($data['24H_change']==0){
					$data['24H_change']=0;
				}
			}else {
				$data['24H_change']=100;
			}
			//7D涨跌
			$re=M('Trade_'.$id)->where("add_time<$time-60*60*24*7")->order('add_time desc')->find();
			if ($re['price']!=0){
				$data['7D_change']=sprintf("%.2f", ($rs['price']-$re['price'])/$re['price']*100);
				if($data['7D_change']==0){
					$data['7D_change']=0;
				}
			}else {
				$data['7D_change']=100;
			}

			//24小时成交量
			$where['add_time'] = array('between',array(time()-86400,time()));
			$where['type'] = 'buy';
			$x = M('Trade_'.$id)->Field('sum(num) as allnum,sum(money) as all_money')->where($where)->find();
			$y = M('Trade_'.$id)->Field('price')->order('price desc')->find();
			$z = M('Trade_'.$id)->Field('price')->order('price asc')->find();
			$data['24H_done_num'] = $x['allnum'];
			//24小时总成交额
			$data['24H_done_money'] = $x['all_money'];
			$data['min_price'] = $z['price'];
			$data['max_price'] = $y['price'];
			$info = M('Currency')->Field('currency_name,currency_mark,currency_logo,currency_all_num')->where('currency_id='.$id)->find();
			//总市值
			$data['currency_all_money'] = $data['new_price']*$info['currency_all_num'];
			$am=M("Trade_".$id)->sum('money');
			$data['currency_am']=$am/2;
			$data['currency_name'] = $info['currency_name'];
			$data['currency_mark'] = $info['currency_mark'];
			$data['currency_logo'] = $info['currency_logo'];
			S('trade_info_'.$id,$data,60);	
		}
// 		dump($data);die();
        return $data;
    }
    //获取对应币种，该会员的资产  ** 修改查询字段
    public function getCurrencyUser($uid,$cid){
        $where['member_id']=$uid;
        $where['currency_id']=$cid;
        $rs=M('Currency_user')->field('cu_id,member_id,currency_id,num,forzen_num,status,chongzhi_url,(num+forzen_num) as count')->where($where)->find();
        return $rs;
    }
    //获取全部币种信息
    public function currency(){
		S('currency',null);
		if(S('currency')){
			$list = S('currency');
		}else{
			$list=M('Currency')->Field('currency_id,currency_name,currency_logo,currency_mark,currency_unit,currency_content,currency_all_num,currency_buy_fee,currency_sell_fee,currency_url,trade_currency_id,is_line,is_lock,port_number,add_time,status,rpc_url,rpc_pwd,rpc_user,currency_all_tibi,detail_url,qianbao_url,qianbao_key,price_up,price_down,sort,currency_digit_num,guanwang_url,currency_fee_reward,start_time_h,end_time_h,end_time_m,start_time_m,is_lock_6,is_lock_7')->where('is_line=1 ')->order('sort')->select();
			S('currency',$list);
		}
// 		dump($list);
        return $list;
    }
    //获取单独币种信息
    public function currency_one($id){
        $list=M('Currency')->Field('currency_id,currency_name,currency_logo,currency_mark,currency_unit,currency_content,currency_all_num,currency_buy_fee,currency_sell_fee,currency_url,trade_currency_id,is_line,is_lock,port_number,add_time,status,rpc_url,rpc_pwd,rpc_user,currency_all_tibi,detail_url,qianbao_url,qianbao_key,price_up,price_down,sort,currency_digit_num,guanwang_url,currency_fee_reward,start_time_h,end_time_h,end_time_m,start_time_m,is_lock_6,is_lock_7')->where("currency_id=".$id)->find();
        return $list;
    }
    //验证前台登录
    public function checkLogin(){
        if (!$_SESSION['USER_KEY'] || !$_SESSION['member_id']) {
            return false;
        }
        return true;
    }

	//空操作
	public function _empty(){
	    header("HTTP/1.0 404 Not Found");
	    $this->display('Public:404');
	}
	
	
	/**
	 * 根据ID返回具体分类
	 * @param string $id
	 * @return boolean|array $list;
	 */

    /**
     * @param $id 用户ID
     * @return bool 返回用户未读消息条数
     */
    public function pullMessageCount($id){
        if(empty($id)){
            return false;
        }
        $count = M('message')->Field('message_id')->where(array('member_id'=>$id,'status'=>0))->count();
        if(empty($count)){
            return 0;
        }
        return $count;
    }
    /**
     * 添加委托表
     * @param  $member_id   用户id
     * @param  $currency_id 币种id
     * @param  $all_num  全部数量
     * @param  $price
     * @param  $type   卖出单1 还是买入单2
     * @param  $fee  手续费
     * @return
     */
    public function addEntrust($member_id,$currency_id,$all_num,$price,$type,$fee){
        $data['member_id']=$member_id;
        $data['currency_id']=$currency_id;
        $data['all_num']=$all_num;
        $data['surplus_num']=$all_num;
        $data['price']=$price;
        $data['add_time']=time();
        $data['type']=$type;
        $data['fee']=$fee;
        $data['status']=0;
        $list=M('Entrust')->add($data);
        if($list){
            return $list;
        }else{
            return false;
        }
    }

   /**
    *  /**
     * 添加消息库
     * @param int $member_id   用户ID -1 为群发
     * @param int $type    分类  4=系统  -1=文章表系统公告 -2 个人信息
     * @param String $title       标题
     * @param String $content     内容
     * @return bool|mixed  成功返回增加Id 否则 false
     */

    public function addMessage_all($member_id,$type,$title,$content){
        $data['u_id']=$member_id;
        $data['type']=$type;
        $data['title']=$title;
        $data['content']=$content;
        $data['add_time']=time();
        $id=M('Message_all')->add($data);
        if($id){
            return $id;
        }else{
            return false;
        }
    }
    /**
     * 添加分表
     * 添加财务日志方法
     * @param unknown $member_id
     * @param unknown $type  
     * @param unknown $content
     * @param unknown $money
     * @param unknown $money_type  收入=1/支出=2
     * @param unknown $currency_id  币种id 0是rmb
     * @return 
     */
    public function addFinance($member_id,$type,$content,$money,$money_type,$currency_id,$time=''){
    	$tid=$member_id%10;
    	$data['member_id']=$member_id;
    	$data['type']=$type;
    	$data['content']=$content;
    	$data['money_type']=$money_type;
    	$data['money']=$money;
    	$data['add_time'] = $time ? $time : time();
    	$data['currency_id']=$currency_id;
        $data['ip'] = get_client_ip();
    	$list=M('Finance_'.$tid)->add($data);
    	if($list){
    		return $list;
    	}else{
    		return false;
    	}
    }
    //修正众筹表 计算剩余数量  修改状态
     public function checkZhongchou(){
     	$list=M('Issue')->field('id,add_time,end_time,num,num_nosell,zhongchou_success_bili,status')->select();
     	foreach($list as $k=>$v){
     		$where['id']=$v['id'];
     		/*if($v['status']==3){
     			M('Issue')->where($where)->setField('end_time',time());
     			continue;
    	 	}*/
     		if($v['add_time']>time()){
     			M('Issue')->where($where)->setField('status',0);
     		}
     		if($v['add_time']<time()&&$v['end_time']>time()){
     			M('Issue')->where($where)->setField('status',1);
    	 	}
    	 	if($v['end_time']<time()){
    	 		M('Issue')->where($where)->setField('status',2);
    	 		//M('Issue')->where($where)->setField('end_time',time());
    	 	}
    	 	$num=M('Issue_log')->Field('num')->where('iid='.$v['id'])->sum('num');
    	 	M('Issue')->where($where)->setField('deal',$v['num']-$num-$v['num_nosell']);
    	 	$limit_num=$v['num']*$v['zhongchou_success_bili']-$v['num_nosell'] ;
    	 	if($num>=$limit_num){
    	 		M('Issue')->where($where)->setField('status',2);
    	 	}
     	}
     }
     //获取会员一次众筹有几次记录
     public function getIssuecountById($uid,$iid){
         if (empty($uid)){
             return 0;
         }
     	$list=M('Issue_log')->Field('id')->where("uid=$uid and iid=$iid")->count();
     	if($list){
     		return $list;
     	}else{
     		return false;
     	}
     }
     //超过时限退出登录方法
     //登录时间存在session里，每次判断当前时间比较，时间过了就清掉SESSION记录
     protected function login_limit_time(){
     	if(!empty($_SESSION['login_time'])){
     		if(!empty($this->config['time_limit'])){
     			if($_SESSION['login_time']<time()-$this->config['time_limit']*60){
     				$_SESSION['login_time']=null;
	     			$_SESSION['member_id']=null;
	       			$_SESSION['USER_KEY']=null;
	       			$_SESSION['STATUS']=null;
	       			$this->redirect('Login/index');
	     		}
     		}
     	}
     	$time=time();
     	$_SESSION['login_time']=$time;
     }
     //设置交易时间，超时不开交易方法
     
     /**
      * 实例化币种
      * @param unknown $currency_id   币种id
      * @return unknown
      */
     public function getCurrencynameById($currency_id){
        if ($currency_id==0){
            return array('currency_name'=>'人民币','currency_mark'=>'CNY','currency_buy_fee'=>0,'currency_sell_fee'=>0);
        }
     	$where['currency_id']= $currency_id;
     	
     	$list = M('Currency')->field('currency_name,currency_mark,currency_buy_fee,currency_sell_fee')->where($where)->find();
     	return $list;
     }
     /**
      *
      * @param int $currency_id 币种id
      * @return array 币种结果集
      */
     protected  function  getCurrencyByCurrencyId($currency_id=0){
		if (empty($currency_id)) {
			$where['currency_id']=array('gt',$currency_id);
		}else{
			$where['currency_id']=array('eq',$currency_id);
		} 	
     	//获取交易币种信息
     	$list= M('Currency')->where($where)->select();
    	
		if (!empty($currency_id)) {
    		return $list[0];  	
     	}else{
     		return $list;
     	}
     }
     
     /**
      * 获取用户名
      * @param unknown $member_id   用户id
      * @return unknown
      */
     public function setUnameById($member_id){
     	 
     	$where['member_id']= $member_id;
     	$list = M('Member')->field('name')->where($where)->find();
     	if(!empty($list)){
     		return $list['name'];
     	}
     }
     /**
      * 设置用户资金表 字段值
      * @param int $member_id  用户id
      * @param int $currenty_id 币种id
      * @param string $key  字段名称
      * @param string $value 字段值
      * @return  boolean 返回执行结果
      */
     protected function  setCurrentyMemberByMemberId($member_id,$currenty_id,$key,$value){
         return   M("Currency_user")->Field($key)->where("member_id=$member_id and  currency_id=$currenty_id")->setField($key,$value);
     }
     /**
      * 获取指定数量个人挂单记录
      * @param int $num 数量
      */
     protected function getOrdersByUser($member_id,$num,$currency_id){
         $where['member_id']=$member_id;
         $where['status']=array('in',array(0,1));
         $where['currency_id']=$currency_id;
         
         return M('Orders')->Field('orders_id,member_id,currency_id,currency_trade_id,price,num,trade_num,fee,type,add_time,trade_time,status')->where($where)->order("add_time desc")->limit($num)->select();   
     }
     
     /**
      * 设置账户资金 $type 1加 2减
      */
      protected   function setUserMoney($member_id,$num,$type,$money_type){
      	//加钱
         if($type==1){
         	$r = M('Member_money')->where(['member_id'=>$member_id])->setInc('money'.$money_type,$num);
         }else{
         	$r = M('Member_money')->where(['member_id'=>$member_id])->setDec('money'.$money_type,$num);
         }
         return $r;

      }
     /**
      * 返回指定状态的挂单记录
      * @param int $status -1 0 1 2
      * @param int $num 数量
      * @param int $currency_id 币种id
      */
    protected function getOrdersByStatus($status,$num,$currency_id){
        $where['currency_id']=$currency_id;
        $where['status']=$status;
        return M('Orders')->Field('orders_id,member_id,currency_id,currency_trade_id,price,num,trade_num,fee,type,add_time,trade_time,status')->where($where)->limit($num)->order('trade_time desc')->select();
    }
     /**
      * 获取指定数量的成交记录
      * @param int $num
      */
     protected function getTradesByNum($num,$currency_id){
         $where['currency_id']=$currency_id;
         return M('Trade')->Field('trade_id,trade_no,member_id,currency_id,currency_trade_id,price,num,money,fee,type,add_time,status')->where($where)->order('add_time desc')->limit($num)->select();
     }
     /**
      *
      获取用户资金
      */
     public function  getUserMoney($member_id,$type){
         $where['member_id']=$member_id;
         $usermoney = M('Member_money')->where($where)->find()['money'.$type];
         return $usermoney;
     }
     /**
      * 返回指定数量排序的挂单记录
      * @param char $type buy sell
      * @param int $num 数量
      * @param char $order 排序 desc asc
      */
       protected function getOrdersByType($currencyid,$type,$num,$order){
         $where['type']=array('eq',$type);
         $where['status']=array('in',array(0,1));
         $where['currency_id']=$currencyid;
         $list= M('Orders')->field("sum(num) as num,sum(trade_num) as trade_num,price,type,status")->where($where)->group('price')->order("price $order, add_time asc")->limit($num)->select();
         foreach ($list as $k=>$v){
             $list[$k]['bili']=100-($v['trade_num']/$v['num']*100);
             $list[$k]['aa']=$v['num']-$v['trade_num'];
         }
         if ($type=='sell'){
           $list=  array_reverse($list);
         }
         return $list;
     }

     
//      /**
//       *撤销订单
//       * @param unknown  Int $list  订货单信息
//       * @param unknown  Int $member_id  用户id
//       * @param unknown  Int $order_id  订单号 id
//       */
//      public function cancelByOrderid($list,$member_id,$order_id){
//      	M()->startTrans();
//      	//dump($list['num']);die;
//      	$num = $list['num'];
//      	$trade_num = $list['trade_num'];
//      	$fee = $list['fee'];
//      	$price = $list['price'];
     
//      	if($list['type']  == "sell" ){
//      		$btype = $list['currency_id'];
//      	}else{
//      		$btype = $list['currency_trade_id'];
//      	}
//      	$num = $num - $trade_num;
//      	if($num == 0){
//      		$info['status'] = 4;
//      		$info['info'] = '没有需要撤销的金额';
//      		return $info;
//      	}
     	 
//      	$whereOrder['orders_id'] = $order_id;
//      	$re[] = M('Orders')->where($whereOrder)->setField('status',-1);
     	 
     	 
//      	if($list['currency_trade_id'] == 0){
//      		$whereCurren['member_id'] = $member_id;
//      		$re[] = M('Member')->where($whereCurren)->setInc('rmb',$num);
//      		$re[] = M('Member')->where($whereCurren)->setDec('forzen_rmb',$num);
//      	}else{
//      		$whereCurren['member_id'] = $member_id;
//      		$whereCurren['currency_id'] = $btype;
//      		$re[] = M('currency_user')->where($whereCurren)->setInc('num',$num);
//      		$re[] = M('currency_user')->where($whereCurren)->setDec('forzen_num',$num);
     		 
//      	}
     
//      	if(!in_array(false, $re)){
//      		M()->commit();
//      		$info['status'] = 2;
//      		$info['info'] = '撤销成功';
//      		return $info;
//      	}else{
//      		M()->rollback();
//      		$info['status'] = 3;
//      		$info['info'] = '撤销失败';
     
//      		return $info;
//      	}
//      }
     /**
      * 获取一个挂单记录价格 买一 卖一
      * @param unknown $currencyid
      * @param unknown $type
      * @param unknown $order
      */
     protected function getOneOrdersByPrice($currencyid,$type){
         $where['currency_id']=$currencyid;
         $where['type']=$type;
         $where['status']=array('in',array(0,1));
         switch ($type){
             case 'buy': $order='desc';
             break;
             case 'sell':$order='asc';
             break;
         }
          $orders= M('Orders')->field('price')->where($where)->order('price '.$order)->find();
          return $orders['price'];
     }
     /**
      * 返回最高价
     @param int $currency_id 币种ID
      */
     protected function getMaxPriceTrade($currency_id){
         $order='desc';
         $trade= $this->getTradeByPrice($currency_id,$order);
         return $trade['price'];
     }
     /**
      * 返回最低价
      @param int $currency_id 币种ID
      */
     protected function getminPriceTrade($currency_id){
         $order='asc';
          $trade= $this->getTradeByPrice($currency_id,$order);
          return $trade['price'];
     }
     /**
      * 指定价格一个成交记录
      * @param int $currency_id 币种ID
      * @param char $order 排序
      */
     private function getTradeByPrice($currency_id,$order){
//          $where['currency_id']=$currency_id;
        return M('Trade_'.$currency_id)->field('price')->where()->order('price '.$order)->find();

     }

     /**
      * 分红奖励全部
      *@param $money 传入交易金额
      *@param $member_id 用户id 不传自动处理登录用户
      */
     protected function dividend($money,$member_id=''){
     	if(empty($member_id)){
     		$userid=$_SESSION['member_id'];
     	}
     	$num=$this->findDividendMinNum();
     	if(!$num){
     		return ;
     	}
     	//max是还可以获得多少个分红股
     	$max=$this->getUserAddDividendPower($member_id,$num);
     	if(!$max){
     		return ;
     	}
     	//增加用户分红业绩
     	if(!$this->addUserDividendNum($money,$member_id,$max,$num)){
     		return;
     	}
     	$this->addDividend($member_id,$num,$max);
     
     }
     /**
      * 增加用户分红业绩
      * @param $money 用户表dividend_num代表分红业绩与金额等比例
      * @param
      * return 成功失败
      */
     private function addUserDividendNum($money,$member_id,$max){
     	if($money>$max*$this->dividendConfig['money'.$max]){
     		$money=$max*$this->dividendConfig['money'.$max];
     	}
     	$res=M('Member')->where('member_id='.$member_id)->setInc('dividend_num',$money);
     	if($res){
     		return true;
     	}else {
     		return false;
     	}
     }
     /**
      * 判断用户进入获得分红股数量是否超过当日上线
      * @param $money 用户表dividend_num代表分红业绩与金额等比例
      * @param
      * return 还可以获得的分红股数
      */
     private function getUserAddDividendPower($member_id,$num){
     	$max=$this->dividendConfig['max'.$num];
     	$today=strtotime(date('Y-m-d 0:0:0'));
     	$count=M('Finance')
     	->where('type=13 and add_time>'.$today.' and member_id='.$member_id)
     	->select();
     	$money=0;
     	if($count){
     		foreach ($count as $k=>$v){
     			$money+=$v['money'];
     		}
     	}
     	if($money<$this->dividendConfig['max'.$num]){
     		return $this->dividendConfig['max'.$num]-$money;
     	}
     	return false;
     }
     /**
      * 获取触发分红业绩
      * return 触发分红业绩后缀
      */
     private function findDividendMinNum(){
     	$num=M('Currency')
     	->field('currency_all_num')
     	->where('currency_id='.$this->dividendConfig['dividend_id'])
     	->find();
     	if($num['currency_all_num']<$this->dividendConfig['num1']*10000){
     		return false;
     	}
     	if($num['currency_all_num']<$this->dividendConfig['num2']*10000){
     		return 1;
     	}
     	if($num['currency_all_num']<$this->dividendConfig['num3']*10000){
     		return 2;
     	}
     	if($num['currency_all_num']<$this->dividendConfig['num4']*10000){
     		return 3;
     	}
     	return false;
     }
     /**
      * 触发分红业绩
      * $num 最少限制
      * $member_id 用户ID
      */
     private function addDividend($member_id,$num,$max){
     	$member=M('Member')
     	->field('dividend_num')
     	->where('member_id='.$member_id)
     	->find();
     	$money=$this->dividendConfig['get'.$num];
     	$n=floor($member['dividend_num']/$this->dividendConfig['money'.$num]);
     	$n=min($n,$max);
     	if($n){
     		M('Member')->where('member_id='.$member_id)->setDec('dividend_num',$this->dividendConfig['money'.$num]*$n);
     		M('Currency')->where("currency_id=".$this->dividendConfig['dividend_id'])->setInc('currency_all_num',$money*$n);
     		$this->setUserMoney($member_id, $this->dividendConfig['dividend_id'],$money*$n, "inc",'num');
     		$this->addFinance($member_id, 13, "获得分红股",$money*$n,1, $this->dividendConfig['dividend_id']);
     
     		return 2;
     	}
     	return 1;
     }
     
     /**
      * ajax 发送手机号码
      */
     public function ajaxSandPhone(){
     	$phone = urldecode($_POST['phone']);
     	if(empty($phone)){
     		$data['status']=0;
     		$data['info'] = "参数错误";
     		$this->ajaxReturn($data);
     	}
     	if(!preg_match("/^1[34578]{1}\d{9}$/",$phone)){
     		$data['status']=-1;
     		$data['info'] = "手机号码不正确";
     		$this->ajaxReturn($data);
     	}
		$ip = get_ip();
		$v = S('ip_phone'.$ip);
		$sss = S('limit_phone_ip');
		if($v > 10){
			$sss[$ip] = 1;
			S('limit_phone_ip',$sss);
		}
		if($sss[$ip] == 1){
			$data['status'] = -8;
			$data['info'] = '此IP已经被禁止发送短信';
			$this->ajaxReturn($data);
		}
     	$r = sandPhone($phone,$this->config['CODE_NAME'],$this->config['CODE_USER_NAME'],$this->config['CODE_USER_PASS']);
     	if($r!="短信发送成功"){
			
			$time = S('ip_phone_time'.$ip);
			if( $time == null || time() - $time > 60 ){
				S('ip_phone_time'.$ip,time());
				S('ip_phone'.$ip,1);
			}else{
				++$v;
				S('ip_phone'.$ip,$v);
				S('ip_phone_time'.$ip,time());
			}
			
     		$data['status']=0;
     		$data['info'] = $r;
     		$this->ajaxReturn($data);
     	}else{
     		$data['status']=1;
     		$data['info'] = $r;
     		$this->ajaxReturn($data);
     	}
     }

     protected function getOrdersDataList(){
     	$currency_or = M ( 'Currency' )->where ( 'is_line=1' )->order ( 'sort' )->select ();
     	$time=time();
        $today=strtotime('-1 day');
        $where['add_time']=array('between',array($today,$time)); // 时间降序排列，越接近当前时间越高
     	foreach ( $currency_or as $k => $v ) {
     		$list = $this->getCurrencyMessageById ( $v ['currency_id'] );
     		$currency_or [$k] = array_merge ( $list, $currency_or [$k] );
     		$trade_total = M ( 'Trade_' . $v ['currency_id'] )->where ( "currency_id={$v['currency_id']}" )->where($where)->sum ( 'money' );
     		$currency_or [$k] ['currency_trade_all'] = number_format ( $trade_total, 2 );
     		$currency_or [$k] ['currency_logo']=$v ['currency_logo'];
     		$currency_or [$k] ['new_price'] = floatval($list ['new_price'] ? $list ['new_price'] : 0);
     		$currency_or [$k] ['currency_all_money'] = number_format ( floatval ( $v ['currency_all_num'] ) * $list ['new_price'], 2 );
     		/* dump($v ['currency_all_num'] );
     		dump($list ['new_price']);die; */
     		$currency_or [$k] ['all_num'] = floatval(M ( "Trade_" . $v ['currency_id'] )->where($where)->sum ( "num" ));
     			
     		// 开盘价
     		$open = $this->getKlineOpen($v['currency_id']);
     		$currency_or [$k] ['kai_price'] = floatval($open);
     		$currency_or [$k] ['price_up']=floatval($v['price_up']);
     		$currency_or [$k] ['price_down']=floatval($v['price_down']);
     		unset ( $kai );
     		// 昨日收盘
     		$wherezuorishoupan ['add_time'] = ['BETWEEN',[strtotime ( date ( "Y-m-d", time () ) ) - 24 * 60 * 60,strtotime ( date ( "Y-m-d", time ()))]];
     		//dump($wherezuorishoupan);die;
     		  // 计算出昨天0点的时候 在计算今天0点时间 取之间最后一笔
     		$zuorishoupan = M ( "Trade_" . $v ['currency_id'] )->field ( "price" )->where ( $wherezuorishoupan )->order ( "trade_id desc" )->limit ( 1 )->find ();
     		$currency_or [$k] ['zuorishoupan'] = $zuorishoupan ['price'];
     		// 收盘价
     		$shoupan = M ( "Trade_" . $v ['currency_id'] )->field ( "price" )->order ( "trade_id desc" )->limit ( 1 )->find ();
     		$currency_or [$k] ['shoupan'] = $shoupan ['price'];
     		// 均价 //五天内的平均价格
     		$wherejunjia ['add_time'] = array (
     				strtotime ( date ( "Y-m-d", time () ) ) - 24 * 60 * 60 * 5,
     				time ()
     		);
     		$junjia = M ( "Trade_" . $v ['currency_id'] )->field ( "sum(price*num) as all_money,sum(num) as num" )->where ( $wherejunjia )->find ();
     		$currency_or [$k] ['junjia'] = round ( $junjia ['all_money'] / $junjia ['num'], 2 );
     		// 现量
     			
     		// 卖价
     		$wheremaijia ['currency_id'] = $v ['currency_id'];
     		$wheremaijia ['type'] = array (
     				'eq',
     				"sell"
     		);
     		$wheremaijia ['status'] = array (
     				'in',
     				array (
     						0,
     						1
     				)
     		);
     		$sell_price = M ( "Orders" )->where ( $wheremaijia )->field ( "price,sum(num) as sell_num" )->order ( "price asc" )->limit ( 1 )->find ();
     		$currency_or [$k] ['sell_price'] = $sell_price ['price'];
     		// 卖量
     		$currency_or [$k] ['sell_num'] = $sell_price ['sell_num'];
     		// 买价
     		$wherebuy ['currency_id'] = $v ['currency_id'];
     		$wherebuy ['type'] = array (
     				'eq',
     				"buy"
     		);
     		$wherebuy ['status'] = array (
     				'in',
     				array (
     						0,
     						1
     				)
     		);
     		$buy_price = M ( "Orders" )->where ( $wherebuy )->field ( "price,sum(num) as buy_num" )->order ( "price desc" )->limit ( 1 )->find ();
     		$currency_or [$k] ['buy_price'] = $buy_price ['price'];
     		// 买量
     		$currency_or [$k] ['buy_num'] = $buy_price ['buy_num'];
     		//涨跌
     		$currency_or [$k] ['zhangfu'] = formatOrderNum($currency_or [$k] ['shoupan']-$currency_or [$k] ['zuorishoupan']); 
     		//涨跌百分比
     		$currency_or [$k] ['zhangfubfb'] = floatval(formatOrderNum(($currency_or [$k] ['new_price']-$currency_or [$k] ['zuorishoupan'])*100/$currency_or [$k] ['zuorishoupan']));
     		// 幅度
     		$currency_or [$k] ['fudu'] = formatOrderNum((($list ['new_price']-$currency_or [$k] ['zuorishoupan'])/$currency_or [$k] ['zuorishoupan'])*100);
     		// dump($currency_or);die;
     		// 最高价格
     		$zuigao = M ( "Trade_" . $v ['currency_id'] )->where($where)->order ( "price desc" )->limit ( 1 )->find ();
  
     		$currency_or [$k] ['zuigao'] = $zuigao ['price'];
     		// 最低价格
     		$zuidi = M ( "Trade_" . $v ['currency_id'] )->where($where)->order ( "price asc" )->limit ( 1 )->find ();
     		$currency_or [$k] ['zuidi'] = $zuidi ['price'];
     		// 现量 现量是指当前一笔的成交量,并不是代表当前只有这么多币种可以买。
     		$xianliang = M ( "Trade_" . $v ['currency_id'] )->field ( "num" )->order ( "trade_id desc" )->limit ( 1 )->find ();
     		$currency_or [$k] ['xianliang'] = $xianliang ['num'];
     		
     	}
     	
     	return $currency_or;
     }
     
     protected function getKlineOpen($currencyId){
     	$map['add_time'] = ['GT',strtotime(date('Y-m-d'))];
     	$open = M ( 'Trade_' . $currencyId )->field ( "price" )->where($map)->order ( 'trade_id asc' )->limit ( 1 )->find ();
     	return $open['price']?$open['price']:0;
     }
     
     
   }

